package publish

import (
	"demo/src/app"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
)

type Project struct {
	Path    string
	Project string
	File    *os.File
}

func init() {
	app.Application.Component(new(PublishService))
}

type PublishService struct {
	app.CommonComponent
}

func (p *PublishService) UploadProject(project Project) error {
	log.Printf("%#v", project)
	name := project.File.Name()
	split := strings.Split(name, ".")
	originFileName := strings.Join(split[3:len(split)-1], ".")
	defer func() {
		project.File.Close()
		os.Remove(name)
	}()
	_, err := project.File.Seek(0, io.SeekStart)
	if err != nil {
		log.Println(err)
		return err
	}
	file, err := os.OpenFile(filepath.Join(project.Path, originFileName), os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0667)
	if err != nil {
		log.Println(err)
		return err
	}
	defer file.Close()
	_, err = io.Copy(file, project.File)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}
